//
//  NetworkEngine.m
//  NetworkAdapter
//
//  Created by bluedaquiri on 16/7/5.
//  Copyright © 2016年 blue. All rights reserved.
//

#import "NetworkEngine.h"
#import "BaseReturnModel.h"
//#import "RegionModel.h"
#define ERROR_AND_CODE(errorMsg, errorCode) [[NSError alloc] initWithDomain:@"" code:errorCode userInfo:@{NSLocalizedDescriptionKey: errorMsg}]

@implementation NetworkEngine

+ (instancetype)shareEngine {
    
    static NetworkEngine *_engine = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        _engine = [[NetworkEngine alloc] initWithBaseURL:[NSURL URLWithString:Main_Token_Model_MANAGER.RootUrl]];
        // 更改超时
        [_engine.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//        _engine.requestSerializer.timeoutInterval = 20.0f;
        _engine.requestSerializer.timeoutInterval = 20;
        [_engine.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        _engine.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        _engine.requestSerializer = [RequestSerializer serializer];
        [_engine.requestSerializer setValue:kHEADERS_VALUE forHTTPHeaderField:kHEADERS_KEY];
        _engine.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/javascript",@"text/json",@"image/png",@"image/jpeg",nil]; // 设置content-Type为text/html
        _engine.responseSerializer = [AFHTTPResponseSerializer serializer];
        
    });
    return _engine;
}

#pragma mark - 请求接口方法
- (void)requestWithPath:(NSString *)path requestParamter:(NSDictionary *)requestParamter reponseObjctClass:(Class)reponseObjctClass completionBlock:(ResponseBlock)completionBlcok {
    
    //参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (requestParamter) {
        for (int i = 0; i<requestParamter.allKeys.count; i++) {
            NSString *key = requestParamter.allKeys[i];
            [parameters setObject:requestParamter[key] forKey:key];
        }
    }
    
    
    
    
    
    [self POST:path parameters:parameters progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject == nil) {
            NSError *error = [NSError errorWithDomain:@"ErrorDomain" code:1 userInfo:@{NSLocalizedDescriptionKey: @"服务器未响应"}];
            completionBlcok(NO, nil, error);
        } else {
            id responseObjectWithJson = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSString *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            //#ifdef DEBUG
            if (parameters) {
                NSLog(@"params : %@", parameters);
            }
            if (responseObjectWithJson){
                NSLog(@"RESPONSE JSON:%@", responseObjectWithJson);
            } else {
                NSLog(@"RESPONSE JSON:%@", result);
            }
            //#endif
            if (reponseObjctClass == nil) {
                if ([[responseObjectWithJson objectForKey:@"code"] integerValue] == 0) {
                    completionBlcok(YES, responseObjectWithJson, nil);
                    return;
                }
                else {

                    NSString *errorMsg = [responseObjectWithJson objectForKey:@"msg"];
                    
                    completionBlcok(NO, responseObjectWithJson, ERROR_AND_CODE(errorMsg, [[responseObjectWithJson objectForKey:@"code"] integerValue]));
                    return;
                }
            }
            if ([[responseObjectWithJson objectForKey:@"code"] integerValue] == 0) {
                //使用YYModel解析json
                id responseClass = [reponseObjctClass yy_modelWithJSON:[responseObjectWithJson objectForKey:@"data"] ];
                if (responseClass) {
                    completionBlcok(YES, responseClass, nil);
                    return;
                }
                //部分接口不需要返回model
                if ([reponseObjctClass isKindOfClass:[BaseReturnModel class]]) {
                    completionBlcok(YES, nil, nil);
                    return;
                }
            }
            else {  //请求返回错误信息
                NSString *errorMsg = [responseObjectWithJson objectForKey:@"msg"];
                completionBlcok(NO, nil, ERROR_AND_CODE(errorMsg, [[responseObjectWithJson objectForKey:@"code"] integerValue]));
                
                return;
            }
            //            }
            NSError *error = [[NSError alloc] initWithDomain:@"ErrorDomain" code:1 userInfo:@{NSLocalizedDescriptionKey : @"网络错误"}];
            completionBlcok(NO, nil, error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
#ifdef DEBUG
        NSString *requestURL = [task.currentRequest.URL absoluteString];
        NSString *params = [[NSString alloc]initWithData:task.currentRequest.HTTPBody encoding:NSUTF8StringEncoding];
        NSLog(@"FAILURE URL:%@ \nPARAMS:%@ \nAND RESPONSE:%@", requestURL, params, task.response);
        if (parameters) {
            NSLog(@"FAILURE  params : %@", parameters);
        }
#endif
        [self showResponseCode:task.response WithBlock:^(NSInteger statusCode) {
            //            [AlertManager alertManagerWithType:alertShowHud title:@"网络异常，稍后再试"];
            completionBlcok(NO, nil, error);
        }];
    }];
}

#pragma mark - Other Manger
- (void)showResponseCode:(NSURLResponse *)response WithBlock:(void (^)(NSInteger statusCode))block{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSInteger responseStatusCode = [httpResponse statusCode];
    return block(responseStatusCode);
}

@end
